# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : variable_options_view.py
# Time       ：2023/10/3 17:43
# Author     ：Y-aong
# version    ：python 3.7
# Description：变量选项
"""

from flask import request
from flask_restx import fields

from apis.options import option_ns
from apis.options.views import option_model
from apis.orderlines.models.variable import Variable
from apis.orderlines.schema.variable_schema import VariableSchema
from public.base_model import db
from public.api_utils.api_decorator import handle_api_error
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView

variable_opt = {'process_id': fields.String()}

variable_opt_marshal = MarshalModel('variable_opt', option_ns)


class VariableOptionView(AbstractView):
    url = '/variable_opt'

    def __init__(self, *args, **kwargs):
        super(VariableOptionView, self).__init__(*args, **kwargs)
        self.process_id = request.args.get('process_id')

    @handle_api_error()
    @option_ns.doc(description='变量选项')
    @option_ns.expect(variable_opt_marshal.detail_request(variable_opt))
    @option_ns.marshal_with(variable_opt_marshal.list_response(option_model, is_db=False))
    def get(self):
        """流程变量选项"""
        objs = db.session.query(Variable).filter(
            Variable.process_id == self.process_id,
            Variable.active == 1
        ).all()
        variable_info = VariableSchema().dump(objs, many=True)
        variable_options = list()
        for item in variable_info:
            temp = {
                'value': '${' + item.get('variable_key') + '}',
                'label': item.get('variable_key')
            }
            variable_options.append(temp)
        return generate_response(variable_options)
